package com.jxwifi.cloud.quickcleanserver.mycenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.basicactivity.BasicActivity;
import com.idroid.widget.LoadDialog;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.InfoBean;
import com.jxwifi.cloud.quickcleanserver.bean.WithdraApplyBean;
import com.jxwifi.cloud.quickcleanserver.bean.WithdraApplyEventBean;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.popwindow.PopRecordModule;
import com.jxwifi.cloud.quickcleanserver.utils.BankCardUtils;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ListUtils;
import cn.trinea.android.common.util.REPattern;

/**
 * 提现
 * Created by Administrator on 2019/5/14.
 */

public class WithdrawalActivity extends CleanBasicActivity {

    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.et_my_authentication_name)
    TextView mEtMyAuthenticationName;//收款人
    @Bind(R.id.et_cash_pank_number)
    TextView mEtCashPankNumber;//银行卡号
    @Bind(R.id.tv_my_authentication_city)
    TextView mtv_my_authentication_city;
    @Bind(R.id.et_cash_withdrawal_price)
    EditText mEtCashWithdrawalPrice;//提现金额
    @Bind(R.id.rel_cash_payee)
    RelativeLayout rll_cash_payee;

    Popwindows popwindow;
    String realName = "";
    String bankName = "";
    String bankNum = "";
    private int flag;

    private List<WithdraApplyBean> mListBean;
    //private LoadDialog mLoadDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cash_withdrawal);
        ButterKnife.bind(this);
        openEventBus();
        initView();
        //mLoadDialog= new LoadDialog(mBaseContext, "");

        flag = getIntent().getIntExtra("flag",0);
        Log.i(TAG,"flag = "+flag);
        if (flag == 2){
            realName = getIntent().getStringExtra("realName");
            bankName = getIntent().getStringExtra("bankName");
            bankNum = getIntent().getStringExtra("bankNum");
            mEtMyAuthenticationName.setText(realName);
            mtv_my_authentication_city.setText(bankName);
            mEtCashPankNumber.setText(bankNum);
        }else {
            mListBean = (List<WithdraApplyBean>)getIntent().getSerializableExtra("list");
            if (mListBean != null){
                mEtMyAuthenticationName.setText(mListBean.get(0).getRealName());
                mtv_my_authentication_city.setText(mListBean.get(0).getBankName());
                mEtCashPankNumber.setText(mListBean.get(0).getBankNum());

                realName = mListBean.get(0).getRealName();
                bankName = mListBean.get(0).getBankName();
                bankNum = mListBean.get(0).getBankNum();
                Log.i(TAG,"mListBean.size() = "+mListBean.size()+" 姓名 = "+mListBean.get(0).getRealName());
            }else {
                withdrawal();
            }
        }






    }

    public void initView(){

        mEtMyAuthenticationName.setText(AccountMgr.getrealName(mBaseContext));
        mEtCashWithdrawalPrice.setHint("可提现"+AccountMgr.getamount(mBaseContext));
        //mEtCashPankNumber.setInputType(InputType.TYPE_NULL);
        mEtCashWithdrawalPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString()!=null&&!TextUtils.isEmpty(s.toString())){
                    if (Double.valueOf(s.toString())>Double.valueOf(AccountMgr.getamount(mBaseContext))){
                        mEtCashWithdrawalPrice.setText(AccountMgr.getamount(mBaseContext));
                    }
                }
            }
        });

    }

    @OnClick({R.id.rel_img_back_pressed,R.id.rel_cash_record,R.id.onCalculateRouteSuccess,R.id.rel_cash_payee})
    void clickCK(View v){
        switch (v.getId()){
            //返回
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
            //记录
            case R.id.rel_cash_record:
                withdrawal();
                break;
            case  R.id.rel_cash_payee:
                Log.i(TAG,"clickCK  rel_cash_payee ==> mListBean = "+mListBean);
                if (null == mListBean) {
                    Intent intent = new Intent(WithdrawalActivity.this, AddCardActivity.class);
                    startActivity(intent);
                } else {
                    Log.i(TAG,"clickCK  rel_cash_payee ==> PopRecordModule  ");
                    PopRecordModule mCityModule = new PopRecordModule(mBaseContext, mListBean, new PopRecordModule.popRecordListener() {
                        @Override
                        public void PopClickTv(String readname, String bankname, String banknum) {
                            mEtMyAuthenticationName.setText(readname);
                            mtv_my_authentication_city.setText(bankname);
                            mEtCashPankNumber.setText(banknum);
                            realName = readname;
                            bankName = bankname;
                            bankNum = banknum;
                        }
                        @Override
                        public void addCard() {
                            Intent intent = new Intent(WithdrawalActivity.this, AddCardActivity.class);
                            startActivity(intent);
                            popwindow.dismiss();
                        }
                    });
                    popwindow = PopWindowUtil.getPopupWindow(mCityModule.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                            .LayoutParams.MATCH_PARENT);
                    mCityModule.setPopwindow(popwindow);
                    popwindow.show(mEtCashWithdrawalPrice, Popwindows.Location.BOTTOM);
                }
                break;
            //确认提现
            case R.id.onCalculateRouteSuccess:
                if (TextUtils.isEmpty(mEtCashPankNumber.getText().toString())){
                    Toast.makeText(mBaseContext,"银行卡号不能为空",Toast.LENGTH_SHORT).show();
                    Toast toast =Toast.makeText(mBaseContext, "银行卡号不能为空", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }

                if (!REPattern.isPrice(mEtCashWithdrawalPrice.getText().toString())){
                    Toast toast =Toast.makeText(mBaseContext, "请输入正确的金额", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                if (Double.valueOf(mEtCashWithdrawalPrice.getText().toString())<10){
                    Toast toast =Toast.makeText(mBaseContext, "提现金额小于10元，不可提现", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                if (Double.valueOf(mEtCashWithdrawalPrice.getText().toString())>Double.valueOf(AccountMgr.getamount(mBaseContext))){
                    Toast toast =Toast.makeText(mBaseContext, "提现超出余额最大值，不可提现", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                //mLoadDialog.show();
                withdrawalCash();
                break;
        }
    }

    public void withdrawal(){
        Params params=new Params();
        params.add("limit",20);
        params.add("page",1);
        Log.i(TAG,"withdrawal ===> ");
        AuzHttp.get(UrlPool.WITHDRAW_APPLY, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                //实体类：WithdraApplyBean
                Log.i(TAG,"withdrawal ===> onSuccess code = "+code);
                if (code==0){
                    JSONObject obj = JSON.parseObject(data);
                    Log.i(TAG,"withdrawal ===> data = "+data);
                    String str = obj.getString("records");
                    Log.i(TAG,"withdrawal ===> str = "+str);
                    mListBean = JSON.parseArray(str, WithdraApplyBean.class);
                    //把相同账户的数据过滤
                    Log.i(TAG,"withdrawal ===> mListBean.size() = "+mListBean.size());
                    for (int i = 0; i < mListBean.size()-1; i++) {
                        for (int j = mListBean.size() - 1; j > i; j--) {
                            Log.i(TAG,"withdrawal ==> mListBean.get(j).getBankNum() = "+mListBean.get(j).getBankNum()+" mListBean.get(i).getBankNum() = "+mListBean.get(i).getBankNum());
                            if (mListBean.get(j).getBankNum().equals(mListBean.get(i).getBankNum())) {
                                mListBean.remove(j);
                                Log.i(TAG,"withdrawal ==> 移除");
                            }
                        }
                    }
                    Log.i(TAG,"withdrawal ===> setText");
                    if (!ListUtils.isEmpty(mListBean)) {
                        mEtMyAuthenticationName.setText(mListBean.get(0).getRealName());
                        mEtCashPankNumber.setText(mListBean.get(0).getBankNum());
                        mtv_my_authentication_city.setText(mListBean.get(0).getBankName());
                        realName = mListBean.get(0).getRealName();
                        bankName = mListBean.get(0).getBankName();
                        bankNum = mListBean.get(0).getBankNum();
                    }

                }else{
                    PasswordLogin.passwordlogin(mBaseContext,TAG, AccountMgr.gettell(mBaseContext),AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin){
                        withdrawal();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);

            }
        },TAG);
    }

    public void withdrawalCash(){
        Params params=new Params();
        params.add("amount",Double.valueOf(mEtCashWithdrawalPrice.getText().toString()));
        params.add("realName",realName);
        params.add("bankName",bankName);
        params.add("bankNum",bankNum);
        Log.i(TAG,"withdrawalCash ==> realName = "+realName+" bankName = "+bankName+" bankNum = "+bankNum);
        AuzHttp.post(UrlPool.CASH_OUT, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                //mLoadDialog.dismiss();
                if (code==0){
                    InfoBean mInfoBean= JSON.parseObject(data, InfoBean.class);
                    AccountMgr.putUser(mBaseContext,mInfoBean,false);
                    Toast toast =Toast.makeText(mBaseContext, "提现成功,金额将在1~3个工作日到账", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    finish();
                }else{
                    PasswordLogin.passwordlogin(mBaseContext,TAG,AccountMgr.gettell(mBaseContext),AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin){
                        withdrawalCash();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                //mLoadDialog.dismiss();
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        },TAG);
    }

    @Subscriber
    public void withdraApplyBeanEventBus(WithdraApplyEventBean withdraApplyBea){

        mEtMyAuthenticationName.setText(withdraApplyBea.getRealName());
        mEtCashPankNumber.setText(withdraApplyBea.getBankNum());
        mtv_my_authentication_city.setText(withdraApplyBea.getBankName());

        realName = withdraApplyBea.getRealName();
        bankName = withdraApplyBea.getBankName();
        bankNum = withdraApplyBea.getBankNum();

        Log.i(TAG,"withdraApplyBeanEventBus ==> realName = "+realName +" bankName = "+bankName);
    }

}
